package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;

public class TmplateVerticle extends AbstractVerticle {

  Router router;
  //第一步声明一个模板引擎
  ThymeleafTemplateEngine thymeleafTemplateEngine;
  @Override
  public void start(Promise<Void> startPromise) throws Exception {

    router =Router.router(vertx);
    //第二步初始化模板引擎
    thymeleafTemplateEngine=ThymeleafTemplateEngine.create(vertx);

    router.route("/").handler(
      req -> {
        //后端传参给前端
        JsonObject entries = new JsonObject();
        entries.put("name","vert.x 2020-10-05");
        //第三步 render 1.JsonObject
        thymeleafTemplateEngine.render(entries,
          "templates/index.html",templates->{
        if (templates.succeeded()){
          req.response()
            //text/plain修改json格式application/json
            .putHeader("content-type", "text/html")
            .end(templates.result());
        } else {

        }
        });

      });


    vertx.createHttpServer().requestHandler(router).listen(8888,http->{
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
